/*
 * @author lb
 * 2012-4-2 添加GroupGeneratorServlet（组考表）
 */
package cn.edu.zjusc.Servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

//import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

//import cn.edu.zjusc.ExcelGenerator.GroupGenerator;
import cn.edu.zjusc.ExcelGenerator.POIAdmissionTicketGenerator;
import cn.edu.zjusc.ExcelModel.ExamSchedule;
//import cn.edu.zjusc.ExcelModel.StudentGroupInfo;
import cn.edu.zjusc.ExcelModel.StudentInfo;
import cn.edu.zjusc.POJO.ExamInfo;
import cn.edu.zjusc.POJO.StudentDetailInfo;
import cn.edu.zjusc.Rmi.IExamRemote;
import cn.edu.zjusc.Rmi.IStudentRemote;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("-----------post---------");
		response.setHeader("Charset", "UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		//response.setContentType("text/json"); // 解决后台数据中文乱码
		response.setCharacterEncoding("UTF-8");

		// 不要多次取writer对象
		PrintWriter out = response.getWriter(); // 输出流
		
		String inApplyNo=request.getParameter("inApplyNo");
		//String inApplyNo="123456";
		BigDecimal inApplyNoBigDecimal=new BigDecimal(inApplyNo);
		System.out.println(inApplyNo);
		
		//RMI访问EJB
		try {
			InitialContext jndiContext=new InitialContext();
			Object ref=jndiContext.lookup("StudentEjbRemote");
			IStudentRemote ss=(IStudentRemote)PortableRemoteObject.narrow(ref, IStudentRemote.class);
			StudentDetailInfo sdiBean=ss.GetStudentDetailInfoByIdName(inApplyNoBigDecimal) ;
			
			//以下为准考证基本信息
			String stuext_examCardID=sdiBean.getExtendInfoBean().getStuext_examCardID();//准考证
			String stubs_name=sdiBean.getStubs_name();//名字
			String stubs_idCard=sdiBean.getStubs_idCard();//身份证
			String stuapl_organization=sdiBean.getApplyInfoBean().getStuapl_organization();//工作单位
			String stuext_examPlace=sdiBean.getExtendInfoBean().getStuext_examPlace();//考试地点
			int stuext_roomNum=sdiBean.getExtendInfoBean().getStuext_roomID();//考场号
			int stuext_seatNumber=sdiBean.getExtendInfoBean().getStuext_seatNumber();//座位号
			String stubs_avatar=sdiBean.getStubs_avatar();//照片

			if(stuext_roomNum==0){
				out.print("<script>alert('对不起，未向该考生分配考场，请为该生添加考场信息。');</script>");
				return ;
			}
			
			System.out.println("---------------adminT-------------");
			System.out.println(stuext_examCardID+","+stubs_name+","+stubs_idCard+","+stuapl_organization+","+stuext_examPlace+","+
					stuext_roomNum+","+stuext_seatNumber+","+stubs_avatar);
			
			//以下为考试信息
			System.out.println("---------------考试信息-------------");
			InitialContext jndiContext2=new InitialContext();
			Object ref2=jndiContext2.lookup("ExamEjbRemote");
			IExamRemote ss2=(IExamRemote)PortableRemoteObject.narrow(ref2, IExamRemote.class);

			List<ExamInfo> examList=ss2.GetAllExamInfoByRoomNum(stuext_roomNum);
			int num=examList.size();
			ExamInfo examInfo1=new ExamInfo();
			ExamInfo examInfo2=new ExamInfo();
			
			//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-kk:m");
			Date date1=new Date();
			Date date2=new Date();
			String dateString1=new String();//考试日期
			String dateString2=new String();//考试日期
			String timeStampAM=new String();//考试时间段
			String timeStampPM=new String();//考试时间段
			String subjectString1=new String();//科目1
			String subjectString2=new String();//科目2
			int duration1,duration2;
			//考试方式：0单自考，1单推荐，2单调剂，3双统考，4双免试
			int examTypeInt=Integer.parseInt(sdiBean.getExtendInfoBean().getStuext_examType());
			//单证推免，一门考试
			System.out.println("-------------------------------------------------examTypeInt:"+examTypeInt);
			System.out.println("-------------------------------------------------num:"+num);
			if(num==1){
				System.out.println("--------------------------推免");
				examInfo1=examList.get(0);
				System.out.println("11111examInfo1:"+examInfo1.getSubject());
				date1=examInfo1.getStartTime();
				dateString1=format.format(date1);
				subjectString1=examInfo1.getSubject();
				//获取考试日期
				dateString1=(format.format(date1)).substring(0, 10);
				//获取考试时间段1
				int startHour=date1.getHours();
				int startMintue=date1.getMinutes();
				duration1=examInfo1.getDuration();
				int endHour=duration1/60+startHour; int endMintue=duration1%60+startMintue;
				String endMintueString=null;
				if(endMintue==0){
					endMintueString="00";
				}else {
					endMintueString=Integer.toString(endMintue);
				}
				if(startMintue!=0){
					timeStampAM=Integer.toString(startHour)+":"+Integer.toString(startMintue)+"-"+Integer.toString(endHour)+":"+endMintueString;
				}else {
					timeStampAM=Integer.toString(startHour)+":"+"00"+"-"+Integer.toString(endHour)+":"+endMintueString;
				}
				
				//生成准考证实例
				POIAdmissionTicketGenerator admissionTicketGenerator_tj=new POIAdmissionTicketGenerator();
				
				//学生信息初始化
				String stuext_examPlaceString=new String();
				if(stuext_examPlace.equals("0")){
					stuext_examPlaceString="杭州";
				}else {
					stuext_examPlaceString="宁波";
				}
				//获取系统路径
				String realWebPhysicalPath = getServletContext().getRealPath(
				"/");
				//判断头像文件是否存在
				String avatarString=realWebPhysicalPath+"userfiles/image/"+inApplyNo+".jpg";
				System.out.println(avatarString);
				File f=new File(avatarString);
				if(!f.exists()){
					avatarString=realWebPhysicalPath+"userfiles/image/noavatar.gif";
				}
				
				StudentInfo student = new StudentInfo(inApplyNo,stuext_examCardID,
						stubs_name,stubs_idCard,"浙江大学",stuapl_organization,stuext_examPlaceString,stuext_roomNum,stuext_seatNumber,avatarString);
				//考场信息初始化
				ExamSchedule schedule = new ExamSchedule(dateString1,dateString1,timeStampAM,"13:30-16:30",subjectString1,"综合测试（面试）");
				//ExamSchedule schedule = new ExamSchedule(dateString1,"",timeStampAM,"",subjectString1,"");
				System.out.println("-----------开始生成---tj-----------");
				
				//模板路径
				String input=realWebPhysicalPath+"userfiles/template/self.xls";
				//文件路径
				String output=realWebPhysicalPath+"userfiles/examcert/"+inApplyNo+".xls";
				//生成准考证
				admissionTicketGenerator_tj.modify_tj(input, output,student,schedule);
				System.out.println("-----------生成结束---tj-----------");
			}
			//单自考，两门考试
			else if (num==2) {
				System.out.println("--------------------------自考");
				examInfo1=examList.get(0);
				examInfo2=examList.get(1);
				System.out.println("22222examInfo1:"+examInfo1.getSubject());			
				date1=examInfo1.getStartTime();
				date2=examInfo2.getStartTime();
				//System.out.println(date1);  //2012-03-01 15:00:00.0
				//获取考试日期
				dateString1=(format.format(date1)).substring(0, 10);
				dateString2=(format.format(date2)).substring(0, 10);
				//获取考试时间段1
				int startHour=date1.getHours();
				int startMintue=date1.getMinutes();
				duration1=examInfo1.getDuration();
				int endHour=duration1/60+startHour; int endMintue=duration1%60+startMintue;
				if(endMintue>=60){
			    	endHour++;
			    	endMintue=endMintue-60;
			    }
				String endMintueString=null;
				if(endMintue==0){
					endMintueString="00";
				}else {
					endMintueString=Integer.toString(endMintue);
				}
				if(startMintue!=0){
					timeStampAM=Integer.toString(startHour)+":"+Integer.toString(startMintue)+"-"+Integer.toString(endHour)+":"+endMintueString;
				}else {
					timeStampAM=Integer.toString(startHour)+":"+"00"+"-"+Integer.toString(endHour)+":"+endMintueString;
				}
				//获取时间段2
				int startHour2=date2.getHours();
				int startMintue2=date2.getMinutes();
				duration2=examInfo2.getDuration();
				int endHour2=duration2/60+startHour2; int endMintue2=duration2%60+startMintue2;
				if(endMintue2>=60){
			    	endHour2++;
			    	endMintue2=endMintue2-60;
			    }
				
				String endMintueString2=null;
				if(endMintue2==0){
					endMintueString2="00";
				}else {
					endMintueString2=Integer.toString(endMintue2);
				}
				if(startMintue2!=0){
					timeStampPM=Integer.toString(startHour2)+":"+Integer.toString(startMintue2)+"-"+Integer.toString(endHour2)+":"+endMintueString2;
				}else {
					timeStampPM=Integer.toString(startHour2)+":"+"00"+"-"+Integer.toString(endHour2)+":"+endMintueString2;
				}
				//获取科目
				subjectString1=examInfo1.getSubject();
				subjectString2=examInfo2.getSubject();
				
				//生成准考证实例
				POIAdmissionTicketGenerator admissionTicketGenerator=new POIAdmissionTicketGenerator();
				//学生信息初始化
				String stuext_examPlaceString=new String();
				if(stuext_examPlace.equals("0")){
					stuext_examPlaceString="杭州";
				}else {
					stuext_examPlaceString="宁波";
				}
				//获取系统路径
				String realWebPhysicalPath = getServletContext().getRealPath(
				"/");
				//判断头像文件是否存在
				String avatarString=realWebPhysicalPath+"userfiles/image/"+inApplyNo+".jpg";
				System.out.println(avatarString);
				File f=new File(avatarString);
				if(!f.exists()){
					avatarString=realWebPhysicalPath+"userfiles/image/noavatar.gif";
				}
				
				StudentInfo student = new StudentInfo(inApplyNo,stuext_examCardID,
						stubs_name,stubs_idCard,"浙江大学",stuapl_organization,stuext_examPlaceString,stuext_roomNum,stuext_seatNumber,avatarString);
				//考场信息初始化
				ExamSchedule schedule = new ExamSchedule(dateString1,dateString2,timeStampAM,timeStampPM,subjectString1,subjectString2);
				//String output="./WebContent/"+inApplyNo+".xls";
				System.out.println("-----------开始生成---zj-----------");
				
				//模板路径
				String input=realWebPhysicalPath+"userfiles/template/self.xls";
				//文件路径
				String output=realWebPhysicalPath+"userfiles/examcert/"+inApplyNo+".xls";
				//生成准考证
				admissionTicketGenerator.modify(input, output,student,schedule);
				System.out.println("-----------生成结束---zj----------");
			}else {
				//考试信息异常，一人大于三场考试
			  out.print("<script>alert('对不起，该生无合法考试数据，请验证该生考试数据。');</script>");
				
			}
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//		} catch (InvalidFormatException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		//传输数据流
		ServletOutputStream outer=null;
		//获取系统路径
		String realWebPhysicalPath = getServletContext().getRealPath(
		"/");
		File file = new File(realWebPhysicalPath+"userfiles/examcert/"+inApplyNo+".xls");
		String fileName = file.getName();
		System.out.println("-----------fileName---------");
		System.out.println(fileName);
		
		if (file.exists() && file.canRead()) {
			response.reset();
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(fileName
									.getBytes("utf-8"),
									"utf-8") + "\"");
			response.setContentLength((int)file.length());
			FileInputStream stream=new FileInputStream(file);	
			try {
				outer=response.getOutputStream();
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = stream.read(buff))) {
					outer.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				System.out.println("IOException." + e);
			} finally {
				//response.setStatus(response.SC_OK);
				//response.flushBuffer();
				System.out.println("-----------final---------");
				stream.close();
				outer.flush();
				outer.close();
				file.delete();
			}
			//return;
		} else {
			//out.println("File Not Found!!!");
		}
		
	}
	
		
			
}
